from models import *
from data_access import *
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login, logout
from django.contrib.auth.models import User


def welcome(request):
    tag = None
    return view(request, 'crt/welcome.html', tag)

def signout(request):
    logout(request)
    return welcome(request)

def signup(request):
    if request.method == 'POST':
        user = User.objects.create_user(request.POST["username"], request.POST["email"], request.POST["password"])
        user.save()
        problem = Problem(name=request.POST["initial_problem"], person=user, status=OPEN, importance=3, is_initial_problem=True)
        problem.save()
        #login(request)
        return home(request)
    tag = None
    return view(request, 'crt/signup.html', tag)

def view(request, template, tag=None):   
    if request.user.is_authenticated():
        welcome_msg = "Welcome, %s" % request.user.username
        json_data = render_json_graph(request.user, tag)
    else:
        welcome_msg = "Welcome, please sign-in to start"
        try:
            user = get_default_user()
            json_data = render_json_graph(user, tag)
        except:
            pass
    importance_choices = Problem.IMPORTANCE_CHOICES
    if request.GET.has_key("problem"):
        effect = request.GET["problem"]
    return render_to_response(template, locals())

@login_required
def home(request, tag=None):
    return view(request, 'crt/home.html', tag)

@login_required
def add(request):
    if request.method == 'POST':
        problem = Problem(name=request.POST["name"], person=request.user)
        problem.populate_from_map(request.POST, request.user)
        problem.save()
        problem.set_tags(request.POST["tags"])
        rel = CausalRelation(person=request.user, cause=problem, effect=get_problem_by_id(request.POST["effect"]))
        rel.save()
        view(request, 'crt/home.html')
    return view(request, 'crt/add.html')

@login_required
def edit(request, key):
    problem = get_object_or_404(Problem, key)
    if request.method == 'POST':
        problem.populate_from_map(request.POST)
        problem.save()
        return HttpResponseRedirect('/')
    return render_to_response('crt/edit.html', locals())

@login_required
def delete(request, key):
    problem = get_object_or_404(Problem, key)
    problem.delete()
    return HttpResponseRedirect('/')


# json rendering

def render_json_graph(user, tag=None):
    problem = get_initial_problem(user)
    if problem == None:
        return "Error: missing initial problem"
    return render_problem_in_json(user, problem, tag)
         
def render_problem_in_json(user, p, tag):
    json = '{"id":"%s","name":"%s","children":[' % (p.id, p.name)
    query = get_problem_causes(user, p)
    # todo further filter by tag
    token = ""
    for rel in query:
        c = rel.cause
        json = "%s %s %s" % (json, token, render_problem_in_json(user, c, tag))
        token = ", "
    json = '%s],"data":[{"key":"weight","value":%d}]}' % (json, p.importance*3)
    return json
